import React, { useEffect, useState } from 'react';
import { Card, Col, Empty, message, Row, Space } from 'antd';
import CallGraphSearch from './CallGraphSearch';
import CallGraphViewer from './CallGraphViewer';
import type { CallGraphData } from './types';
import { queryCallGraph, getRecommendedPath } from '../../../services/callGraphService';

interface Props { unitId: string; }

const CallGraphTab: React.FC<Props> = ({ unitId }) => {
  const [graphData, setGraphData] = useState<CallGraphData | null>(null);
  const [loading, setLoading] = useState(false);
  const [isInitialLoad, setIsInitialLoad] = useState(true);

  // 组件加载时自动获取推荐链路
  useEffect(() => {
    const loadRecommendedPath = async () => {
      if (!unitId) return;
      setLoading(true);
      try {
        const res: any = await getRecommendedPath(unitId);
        const data = res?.data || res;
        if (data && data.nodes && data.nodes.length > 0) {
          setGraphData(data);
        }
      } catch (e: any) {
        // 静默失败，不显示错误提示（因为可能是Neo4j未配置）
        console.warn('获取推荐链路失败:', e?.message);
      } finally {
        setLoading(false);
        setIsInitialLoad(false);
      }
    };
    loadRecommendedPath();
  }, [unitId]);

  const handleSearch = async (p: { target: string; queryType: 'METHOD' | 'TABLE'; depth: number; includeUpstream: boolean; includeDownstream: boolean; }) => {
    if (!p.target) { message.warning('请输入查询目标'); return; }
    setLoading(true);
    try {
      const res: any = await queryCallGraph({
        unitId,
        target: p.target,
        queryType: p.queryType,
        depth: p.depth,
        includeUpstream: p.includeUpstream,
        includeDownstream: p.includeDownstream
      });
      setGraphData(res?.data || res);
    } catch (e: any) {
      message.error(e?.message || '查询调用关系图失败');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="call-graph-container">
      <Row gutter={16}>
        <Col span={24}>
          <Card>
            <Space direction="vertical" style={{ width: '100%' }}>
              <CallGraphSearch unitId={unitId} onSearch={handleSearch} loading={loading} />
            </Space>
          </Card>
        </Col>
      </Row>

      <Row gutter={16} style={{ marginTop: 16 }}>
        <Col span={24}>
          <Card>
            {loading && isInitialLoad ? (
              <div style={{ textAlign: 'center', padding: '100px 0' }}>
                <Empty description="正在加载推荐链路..." />
              </div>
            ) : graphData ? (
              <CallGraphViewer data={graphData} loading={loading} />
            ) : (
              <Empty description="请输入搜索条件查询调用关系图" />
            )}
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default CallGraphTab;

